#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# ----------------------------------------------------------
# -- This's socket client
# -- 
# ****************************
# Author: lmay.Zhou
# Blog: www.lmaye.com
# Date: 2017年8月2日 18:07:11
# ----------------------------------------------------------

import socket
import time
from files.logs import Logger
from files.tools import ConfigUtils


class SocketClient(object):
    """
        初始化 SocketClient建立socket连接\n
        socket 类型	描述\n
        socket.AF_UNIX ---> 用于同一台机器上的进程通信（既本机通信）\n
        socket.AF_INET ---> 用于服务器与服务器之间的网络通信\n
        socket.AF_INET6 ---> 基于IPV6方式的服务器与服务器之间的网络通信\n
        socket.SOCK_STREAM ---> 基于TCP的流式socket通信\n
        socket.SOCK_DGRAM ---> 基于UDP的数据报式socket通信\n
        socket.SOCK_RAW ---> 原始套接字，普通的套接字无法处理ICMP、IGMP等网络报文，而SOCK_RAW可以；其次SOCK_RAW也可以处理特殊的IPV4报文；此外，利用原始套接字，可以通过IP_HDRINCL套接字选项由用户构造IP头\n
        socket.SOCK_SEQPACKET ---> 可靠的连续数据包服务
    """
    _log = Logger.log();

    def __init__(self):
        self.clientSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM);
        # 设置超时时间
        self.timeout = 60;
        # socket.setdefaulttimeout(timeout);
        self.clientSocket.settimeout(self.timeout);
        # 获取本地主机
        # host = socket.gethostname();
        self.conf = ConfigUtils();
        self.host = self.conf.readConfig("server_host", section="server");
        self.port = self.conf.readConfig("server_port", section="server");
        try:
            # 建立连接
            self.clientSocket.connect((self.host, int(self.port)));
        except ConnectionRefusedError as e:
            self._log.error(e);
        # 非阻塞模式
        self.clientSocket.setblocking(0);

    # 发送消息
    def sendMsg(self, msg):
        if None is msg:
            self._log.error("msg is None ...");
            return;
        self.clientSocket.sendall(msg.encode("UTF-8"));

    # 接收消息
    def receiveMsg(self):
        # 延迟0.8秒
        time.sleep(0.8);
        i = 1;
        msgLen = 0;
        result = "";
        while True:
            msg = self.clientSocket.recv(128);
            msgLen += len(msg);
            self._log.info("--> {} - {}".format(len(msg), msg));
            result += msg.decode("UTF-8");
            if 1 == i:
                length = int(msg[:10]);
                i += i;
            self._log.info("length : {} msgLen : {}".format(length, msgLen));
            if msgLen - 10 == length:
                break;
        self._log.info("接收数据: \n%s", result[10:]);
        self.clientSocket.close();
        return result[10:];
